<template>
  <view class="landlord-manage-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">房东管理</text>
      <text class="nav-add" @click="showAddModal">新增</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="请输入房东姓名"
        @confirm="handleSearch"
        @clear="handleClear"
        @input="handleInput"
      />
    </view>


    <!-- 房东列表 -->
    <view class="landlord-list">
      <view 
        class="landlord-item" 
        v-for="item in landlordList" 
        :key="item.userId"
        @click="viewDetail(item)"
      >
        <view class="item-header">
          <view class="avatar-section">
            <view class="avatar">
              <text class="avatar-text">{{ item.nickName.slice(0, 1) }}</text>
            </view>
            <view class="info">
              <text class="name">{{ item.nickName || item.userName }}</text>
              <text class="phone">{{ item.phonenumber }}</text>
            </view>
          </view>
          <text class="item-status" :class="getStatusClass(item.status)">
            {{ getStatusText(item.status) }}
          </text>
        </view>
        <view class="item-content">
          <view class="item-row">
            <text class="item-label">用户名：</text>
            <text class="item-value">{{ item.userName }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">昵称：</text>
            <text class="item-value">{{ item.nickName || '未设置' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">邮箱：</text>
            <text class="item-value">{{ item.email || '未设置' }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">注册时间：</text>
            <text class="item-value">{{ formatDate(item.createTime) }}</text>
          </view>
        </view>
        <view class="item-footer">
          <view class="item-actions">
            <text class="action-btn edit" @click.stop="editLandlord(item)">编辑</text>
            <text class="action-btn contact" @click.stop="contactLandlord(item)">联系</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="landlordList.length === 0 && !loading">
      <text class="empty-text">暂无房东信息</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 新增房东弹窗 -->
    <uni-popup ref="addPopup" type="bottom">
      <view class="add-popup">
        <view class="popup-header">
          <text class="popup-title">新增房东</text>
          <text class="popup-close" @click="$refs.addPopup.close()">×</text>
        </view>
        <view class="popup-content">
          <view class="form-item">
            <text class="form-label">房东姓名</text>
            <uni-easyinput
              v-model="addForm.nickName"
              placeholder="请输入房东姓名"
              :clearable="true"
            />
          </view>
          <view class="form-item">
            <text class="form-label">手机号码</text>
            <uni-easyinput
              v-model="addForm.userName"
              placeholder="请输入手机号码"
              :clearable="true"
            />
          </view>
          <view class="form-item">
            <text class="form-label">手机号码确认</text>
            <uni-easyinput
              v-model="addForm.phonenumber"
              placeholder="请再次输入手机号码"
              :clearable="true"
            />
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="$refs.addPopup.close()">取消</button>
          <button class="btn-confirm" @click="confirmAdd">确认新增</button>
        </view>
      </view>
    </uni-popup>

    <!-- 编辑房东弹窗 -->
    <uni-popup ref="editPopup" type="bottom">
      <view class="edit-popup">
        <view class="popup-header">
          <text class="popup-title">编辑房东</text>
          <text class="popup-close" @click="$refs.editPopup.close()">×</text>
        </view>
        <view class="popup-content">
          <view class="form-item">
            <text class="form-label">房东姓名</text>
            <uni-easyinput
              v-model="editForm.nickName"
              placeholder="请输入房东姓名"
              :clearable="true"
            />
          </view>
          <view class="form-item">
            <text class="form-label">手机号码</text>
            <uni-easyinput
              v-model="editForm.phonenumber"
              placeholder="请输入手机号码"
              :clearable="true"
            />
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="$refs.editPopup.close()">取消</button>
          <button class="btn-confirm" @click="confirmEdit">确认修改</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getLandlordList, addLandlord } from '@/api/door/house'
import { updateUser } from '@/api/system/user'

export default {
  data() {
    return {
      searchKeyword: '',
      stats: {
        totalCount: 0,
        activeCount: 0,
        houseCount: 0
      },
      landlordList: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      addForm: {
        nickName: '',
        userName: '',
        phonenumber: ''
      },
      editForm: {
        userId: '',
        nickName: '',
        phonenumber: ''
      },
      statusOptions: [
        { value: '0', text: '正常' },
        { value: '1', text: '禁用' }
      ]
    }
  },
  onLoad() {
    this.loadData()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData()
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 显示新增弹窗
    showAddModal() {
      this.$refs.addPopup.open()
    },
    
    // 处理搜索
    handleSearch() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 处理清空
    handleClear() {
      this.searchKeyword = ''
      this.pageNum = 1
      this.loadData()
    },
    
    // 处理输入
    handleInput() {
      // 可以在这里实现实时搜索
    },
    
    // 加载数据
    async loadData() {
      if (this.loading) return
      
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          roleId: 100 // 房东角色ID
        }
        
        // 添加搜索关键词
        if (this.searchKeyword) {
          params.nickName = this.searchKeyword
        }
        
        console.log('查询房东参数:', params)
        const response = await getLandlordList(params)
        
        if (response.code === 200) {
          if (this.pageNum === 1) {
            this.landlordList = response.rows || []
          } else {
            this.landlordList = [...this.landlordList, ...(response.rows || [])]
          }
          
          this.hasMore = response.rows && response.rows.length === this.pageSize
          
          // 更新统计数据
          this.updateStats()
          
          console.log('房东数据:', response.total, '条')
        } else {
          this.$modal.msgError(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 更新统计数据
    updateStats() {
      this.stats.totalCount = this.landlordList.length
      this.stats.activeCount = this.landlordList.filter(item => item.status === '0').length
      this.stats.houseCount = 0 // 暂时设为0，后续可以通过其他接口获取
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.loadData()
    },
    
    // 加载更多
    loadMore() {
      this.pageNum++
      this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/landlord/detail?id=${item.userId}`
      })
    },
    
    // 编辑房东
    editLandlord(item) {
      // 填充编辑表单数据
      this.editForm = {
        userId: item.userId,
        nickName: item.nickName || '',
        phonenumber: item.phonenumber || ''
      }
      // 打开编辑弹窗
      this.$refs.editPopup.open()
    },
    
    // 联系房东
    contactLandlord(item) {
      uni.showActionSheet({
        itemList: ['拨打电话'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 拨打电话
            uni.makePhoneCall({
              phoneNumber: item.phonenumber
            })
          } else if (res.tapIndex === 1) {
            // 发送短信
            uni.sendSms({
              phoneNumber: item.phonenumber,
              content: '您好，我是门禁系统管理员，有关于您房产的事项需要沟通。'
            })
          }
        }
      })
    },
    
    // 获取状态样式
    getStatusClass(status) {
      if (status === '0') {
        return 'status-active'
      } else {
        return 'status-inactive'
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      if (status === '0') {
        return '正常'
      } else {
        return '禁用'
      }
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 确认新增房东
    async confirmAdd() {
      if (!this.addForm.nickName || !this.addForm.userName || !this.addForm.phonenumber) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }

      if (this.addForm.userName !== this.addForm.phonenumber) {
        uni.showToast({
          title: '两次输入的手机号码不一致',
          icon: 'none'
        });
        return;
      }

      this.loading = true;
      try {
        const data = {
          userName: this.addForm.userName,
          nickName: this.addForm.nickName,
          password: '123456', // 默认密码
          phonenumber: this.addForm.phonenumber,
          status: '0',
          postIds: [],
          roleIds: [100] // 房东角色ID
        };
        
        console.log('新增房东数据:', data);
        const response = await addLandlord(data);
        
        if (response.code === 200) {
          uni.showToast({
            title: '新增成功',
            icon: 'success'
          });
          this.$refs.addPopup.close();
          this.resetAddForm();
          this.loadData(); // 刷新列表
        } else {
          uni.showToast({
            title: response.msg || '新增失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('新增房东失败:', error);
        // uni.showToast();
      } finally {
        this.loading = false;
      }
    },
    
    // 确认编辑房东
    async confirmEdit() {
      if (!this.editForm.nickName || !this.editForm.phonenumber) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }

      this.loading = true;
      try {
        const data = {
          userId: this.editForm.userId,
          nickName: this.editForm.nickName,
          userName: this.editForm.nickName,
          phonenumber: this.editForm.phonenumber,
          password: '123456', // 默认密码
          postIds: [],
          roleIds: [100], // 房东角色ID
          status: '0'
        };
        
        console.log('编辑房东数据:', data);
        const response = await this.updateLandlord(data);
        
        if (response.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          });
          this.$refs.editPopup.close();
          this.loadData(); // 刷新列表
        } else {
          uni.showToast({
            title: response.msg || '修改失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('编辑房东失败:', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 更新房东信息
    async updateLandlord(data) {
      return await updateUser(data);
    },
    
    // 重置新增表单
    resetAddForm() {
      this.addForm = {
        nickName: '',
        userName: '',
        phonenumber: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.landlord-manage-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-add {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.search-bar {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
}

.stats-section {
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  
  .stats-item {
    text-align: center;
    
    .stats-num {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.landlord-list {
  padding: 20rpx;
}

.landlord-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .avatar-section {
      display: flex;
      align-items: center;
      flex: 1;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background-color: #007AFF;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 20rpx;
        
        .avatar-text {
          color: #fff;
          font-size: 32rpx;
          font-weight: bold;
        }
      }
      
      .info {
        .name {
          display: block;
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .phone {
          font-size: 26rpx;
          color: #666;
        }
      }
    }
    
    .item-status {
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      &.status-active {
        background-color: #e8f5e8;
        color: #52c41a;
      }
      
      &.status-inactive {
        background-color: #f0f0f0;
        color: #666;
      }
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
    }
  }
  
  .item-content {
    .item-row {
      display: flex;
      margin-bottom: 15rpx;
      
      .item-label {
        font-size: 26rpx;
        color: #666;
        width: 140rpx;
      }
      
      .item-value {
        font-size: 26rpx;
        color: #333;
        flex: 1;
        
        &.amount {
          color: #52c41a;
          font-weight: bold;
        }
      }
    }
  }
  
  .item-footer {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
    
    .item-actions {
      display: flex;
      gap: 20rpx;
      
      .action-btn {
        font-size: 24rpx;
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        
        &.edit {
          background-color: #e6f7ff;
          color: #1890ff;
        }
        
        &.view {
          background-color: #f6ffed;
          color: #52c41a;
        }
        
        &.contact {
          background-color: #fff7e6;
          color: #fa8c16;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

.add-popup, .edit-popup {
  padding: 30rpx;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  position: relative;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .popup-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }

    .popup-close {
      font-size: 40rpx;
      color: #999;
      font-weight: bold;
    }
  }

  .popup-content {
    .form-item {
      margin-bottom: 30rpx;
      display: flex;
      align-items: center;

      .form-label {
        font-size: 28rpx;
        color: #333;
        width: 180rpx;
        margin-right: 20rpx;
      }

      .uni-easyinput, .uni-data-select {
        flex: 1;
        border: 1px solid #eee;
        border-radius: 10rpx;
        padding: 10rpx 20rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .popup-footer {
    display: flex;
    justify-content: space-around;
    padding-top: 30rpx;
    border-top: 1px solid #eee;

    .btn-cancel, .btn-confirm {
      flex: 1;
      text-align: center;
      padding: 15rpx 0;
      border-radius: 30rpx;
      font-size: 32rpx;
      font-weight: bold;
      margin: 0 10rpx;
    }

    .btn-cancel {
      background-color: #f0f0f0;
      color: #333;
      border: 1px solid #eee;
    }

    .btn-confirm {
      background-color: #007AFF;
      color: #fff;
    }
  }
}
</style> 